# -*- coding: utf-8 -*-

from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

from piston.handler import AnonymousBaseHandler, BaseHandler
from piston.utils import rc

from fluffyshare.settings import MEDIA_ROOT, PROVIDER_NAME
from fluffyshare.provider.models import File
import base64

import os

try:
    import simplejson as json
except ImportError:
    import json

# http://domain/api/get-file
class RemoteFileHandler(AnonymousBaseHandler):
    allowed_methods = ('PUT',)
    
    def update(self, request):
        postdata = json.loads(request.raw_post_data)
        sp_from = postdata['service-provider']
        user = postdata['username']
        filename = postdata['filename']
        found = True
        filecontent = None
        status = 'OK'
        fullpath = os.path.join(MEDIA_ROOT, filename)
        
        try:
            File.objects.get(path = filename)
            filecontent = open(fullpath).read()
        except:
            found = False
        if not found:
            status = 'NOT FOUND'
        if filecontent:
            filecontent = base64.b64encode(filecontent)
        return {'service-provider': PROVIDER_NAME,
                'username': user,
                'status': status,
                'filename': filename,
                'full path': fullpath,
                'data': filecontent }
